package com.dkd.system.controller;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.dkd.common.config.RuoYiConfig;
import com.dkd.common.exception.ServiceException;
import com.dkd.framework.config.ServerConfig;
import com.dkd.system.utils.StoragePathUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.dkd.common.annotation.Log;
import com.dkd.common.core.controller.BaseController;
import com.dkd.common.core.domain.AjaxResult;
import com.dkd.common.enums.BusinessType;
import com.dkd.system.domain.TTemplate;
import com.dkd.system.service.ITTemplateService;
import com.dkd.common.utils.poi.ExcelUtil;
import com.dkd.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * templateController
 * 
 * @author chuyongshuo
 * @date 2025-08-07
 */
@RestController
@RequestMapping("/warranty/template")
public class TTemplateController extends BaseController
{
    @Autowired
    private ITTemplateService tTemplateService;

    @Autowired
    private ServerConfig serverConfig;

    @Value("${ruoyi.template.json.storage-path}")
    private String storagePath; // 在application.yml中配置存储路径，如: D:/template-json/


    /**
     * 查询template列表
     */
    @PreAuthorize("@ss.hasPermi('warranty:template:list')")
    @GetMapping("/list")
    public TableDataInfo list(TTemplate tTemplate)
    {
        startPage();
        List<TTemplate> list = tTemplateService.selectTTemplateList(tTemplate);
        return getDataTable(list);
    }

    /**
     * 查询template所有数据
     */
    @PreAuthorize("@ss.hasPermi('warranty:template:list')")
    @GetMapping("/allList")
    public AjaxResult getAllTemplate()
    {
        List<TTemplate> list = tTemplateService.getAllTemplate();
        return AjaxResult.success(list);
    }

    /**
     * 导出template列表
     */
    @PreAuthorize("@ss.hasPermi('warranty:template:export')")
    @Log(title = "EXCEL模板", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TTemplate tTemplate)
    {
        List<TTemplate> list = tTemplateService.selectTTemplateList(tTemplate);
        ExcelUtil<TTemplate> util = new ExcelUtil<TTemplate>(TTemplate.class);
        util.exportExcel(response, list, "template数据");
    }

    /**
     * 获取template详细信息
     */
    @PreAuthorize("@ss.hasPermi('warranty:template:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        return success(tTemplateService.selectTTemplateById(id));
    }

    @PostMapping("/save")
    @PreAuthorize("@ss.hasPermi('warranty:template:query')")
    public AjaxResult saveJsonTemplate(
            @RequestPart("file") MultipartFile file,
            @RequestParam String id,
            @RequestParam(required = false, defaultValue = "0") String status) {

        try {
            // 1. 验证文件非空
            if (file.isEmpty()) {
                return AjaxResult.error("文件不能为空");
            }

            // 2. 读取并验证JSON（自动释放资源）
            String jsonContent;
            try (InputStream is = file.getInputStream()) {
                jsonContent = new String(is.readAllBytes(), StandardCharsets.UTF_8);
                new ObjectMapper().readTree(jsonContent); // 验证JSON有效性
            }

            // 3. 处理文件存储
            String finalFilePath;
            boolean isOverwrite = "1".equals(status);

            if (isOverwrite) {
                // 3.1 覆盖模式：使用原路径
                TTemplate oldTemplate = tTemplateService.selectTTemplateById(Integer.valueOf(id));
                if (oldTemplate == null || StringUtils.isEmpty(oldTemplate.getJsonData())) {
                    return AjaxResult.error("未找到可覆盖的模板");
                }
                // 直接覆盖原文件内容
                Files.write(
                        Paths.get(oldTemplate.getJsonData()),
                        jsonContent.getBytes(StandardCharsets.UTF_8),
                        StandardOpenOption.TRUNCATE_EXISTING,
                        StandardOpenOption.WRITE
                );
                finalFilePath = oldTemplate.getJsonData();
            } else {
                // 3.2 新增模式：使用工具类生成带目录的文件路径
                String filename = "template_" + id + "_" + System.currentTimeMillis() + ".json";
                finalFilePath = StoragePathUtils.storeFileStream(storagePath, filename,
                        new ByteArrayInputStream(jsonContent.getBytes(StandardCharsets.UTF_8)));
            }

            // 4. 更新数据库记录
            tTemplateService.updateTTemplateJson(id, finalFilePath);

            return AjaxResult.success(isOverwrite ? "覆盖成功" : "新增成功");

        } catch (JsonProcessingException e) {
            return AjaxResult.error("无效的JSON格式");
        } catch (IOException e) {
            return AjaxResult.error("文件操作失败: " + e.getMessage());
        }
    }
    /**
     * 获取template模板JSON
     */
    @PreAuthorize("@ss.hasPermi('warranty:template:query')")
    @GetMapping(value = "/preview/{id}")
    public void getPreviewJsonById(@PathVariable("id") Integer id, HttpServletResponse response) {
        logger.info("查看模板,id是{}", id);
        try {
            // 1. 查询模板记录获取文件路径
            TTemplate tTemplate = tTemplateService.selectTTemplateById(id);
            if (tTemplate == null || StringUtils.isEmpty(tTemplate.getJsonData())) {
                response.sendError(HttpStatus.NOT_FOUND.value(), "模板不存在或未关联JSON文件");
                return;
            }

            // 2. 读取文件内容
            Path filePath = Paths.get(tTemplate.getJsonData());
            if (!Files.exists(filePath)) {
                response.sendError(HttpStatus.NOT_FOUND.value(), "JSON文件不存在");
                return;
            }

            // 3. 设置响应头
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "inline; filename=template_" + id + ".json");

            // 4. 文件流式传输
            Files.copy(filePath, response.getOutputStream());

        } catch (IOException e) {
            logger.error("获取模板JSON数据失败", e);
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
     /*   logger.info("查看模板,id是{}", id);
        try {
            // 1. 查询模板数据
            TTemplate tTemplate = tTemplateService.selectTTemplateJsonById(id);
            if (tTemplate == null || tTemplate.getJsonData() == null) {
                response.sendError(HttpStatus.NOT_FOUND.value(), "模板不存在或没有JSON数据");
                return;
            }

            // 2. 获取JSON字符串
            String jsonData = tTemplate.getJsonData();

            // 3. 设置响应头
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=template_" + id + ".json");

            // 4. 将JSON转为二进制写入响应流
            try (OutputStream out = response.getOutputStream()) {
                out.write(jsonData.getBytes(StandardCharsets.UTF_8));
                out.flush();
            }

        } catch (IOException e) {
            logger.error("获取模板JSON数据失败", e);
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }*/
    }

    /**
     * 获取template模板文件流
     */
    @PreAuthorize("@ss.hasPermi('warranty:template:query')")
    @GetMapping(value = "/getTemplateBlob/{id}")
    public void getPreviewById(@PathVariable("id") Integer id, HttpServletResponse response) {
        logger.info("查看模板,id是{}",id);
        // 获取模板信息
        TTemplate template = tTemplateService.selectTTemplateById(id);
        if (template == null || StringUtils.isEmpty(template.getFileLocation())) {
            throw new ServiceException("模板不存在或文件位置为空");
        }
        // 获取文件上传路径
        String filePath = RuoYiConfig.getUploadPath();
        String fileLocation = template.getFileLocation(); // profile/upload/2025/08/09/tem1_20250809115209A001.xlsx
        String relativePath = fileLocation.replaceAll("^.*?upload", "");
        // 解析文件名和后缀
        String originalFilename = fileLocation.substring(fileLocation.lastIndexOf("/") + 1);
        String fileNameWithoutExt = originalFilename.substring(0, originalFilename.lastIndexOf(".")); //文件后缀
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1); //文件名
        try (FileInputStream fis = new FileInputStream(filePath + relativePath)) {
            // 设置响应头 - 使用原始文件名
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(originalFilename, "UTF-8"));
            // 将文件流写入响应
            IOUtils.copy(fis, response.getOutputStream());
            response.flushBuffer();
        } catch (IOException e) {
            throw new ServiceException("查看模板文件失败");
        }
    }
    /**
     * 获取template模板文件流(blob数组方式)
     */
    @PreAuthorize("@ss.hasPermi('warranty:template:query')")
    @GetMapping(value = "/preview1/{id}")
    public ResponseEntity<byte[]> getPreviewById(@PathVariable("id") Integer id) {
        logger.info("查看模板,id是{}", id);
        // 获取模板信息
        TTemplate template = tTemplateService.selectTTemplateById(id);
        if (template == null || StringUtils.isEmpty(template.getFileLocation())) {
            throw new ServiceException("模板不存在或文件位置为空");
        }

        // 获取文件上传路径
        String filePath = RuoYiConfig.getUploadPath();
        String fileLocation = template.getFileLocation(); // profile/upload/2025/08/09/tem1_20250809115209A001.xlsx
        String relativePath = fileLocation.replaceAll("^.*?upload", "");

        // 解析文件名
        String originalFilename = fileLocation.substring(fileLocation.lastIndexOf("/") + 1);

        try {
            // 读取文件为字节数组
            byte[] fileContent = Files.readAllBytes(Paths.get(filePath + relativePath));

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", URLEncoder.encode(originalFilename, "UTF-8"));

            return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
        } catch (IOException e) {
            throw new ServiceException("查看模板文件失败");
        }
    }

    /**
     * 新增template
     */
    @PreAuthorize("@ss.hasPermi('warranty:template:add')")
    @Log(title = "EXCEL模板", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TTemplate tTemplate)
    {
        int count = tTemplateService.insertTTemplate(tTemplate);
        Integer id = tTemplate.getId();
        return AjaxResult.success(id);
    }

    /**
     * 修改template
     */
    @PreAuthorize("@ss.hasPermi('warranty:template:edit')")
    @Log(title = "EXCEL模板", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TTemplate tTemplate)
    {
        return toAjax(tTemplateService.updateTTemplate(tTemplate));
    }

    /**
     * 删除template
     */
    @PreAuthorize("@ss.hasPermi('warranty:template:remove')")
    @Log(title = "EXCEL模板", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {
        return toAjax(tTemplateService.deleteTTemplateByIds(ids));
    }
}
